package com.groot.springbootmybatis.common;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * Mybatis配置，只读
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.groot.springbootmybatis.dao.mapper","com.groot.springbootmybatis.dao.mapper"})
public class MiddleMybatisConfig {

    @Bean(name = "middleMybatisSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("octMybatisDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/mapper/*.xml";
        bean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
        return bean.getObject();
    }

    @Bean(name = "middleMybatisSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("middleMybatisSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
